<?php
$post = $_POST;
try {
    if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $tmpName = $_FILES['file']['tmp_name'];
        $chunkIndex = $_POST['chunk_index'];
        $totalChunks = $_POST['total_chunks'];
        $fileName = './tmp/uploaded_file.tmp';

        // 合并文件
        if ($chunkIndex === 0) {
            $out = fopen($fileName, 'wb');
        } else {
            $out = fopen($fileName, 'ab');
        }

        if (!$out) {
            echo '打开文件失败 '.$fileName;exit;
        }

        $_wirte_res = fwrite($out, file_get_contents($tmpName), $_FILES['file']['size']);
        if (!$_wirte_res) {
            echo json_encode([
                'code' => 0, 'msg' => '写文件失败 '.$tmpName. ' size: '.$_FILES['file']['size'], 'filePath' => $fileName,
            ]);exit;
        }
        fclose($out);
        fclose($in);

        $fileSize = filesize($fileName);
        if (1 > $fileSize) {
            echo json_encode([
                'code' => 0, 'msg' => '文件合并失败 '.$tmpName, 'filePath' => $fileName,
            ]);exit;
        }


        if ($chunkIndex == ($totalChunks - 1)) {
            //move file to current path
            $post['fileName'] = str_replace(' ', '', $post['fileName']);
            $finalFileName = 'u'.$post['fileName'];
            switch ($post['fileType']) {
                case 'imgZip':
                    $finalFileName = './images/'.$finalFileName;
                    break;
                case 'videoZip':
                    $finalFileName = './media/'.$finalFileName;
                    break;
                case 'emailZip':
                    $finalFileName = './emailimg/'.$finalFileName;
                    break;
            }
            if (file_exists($finalFileName)) {
                unlink($finalFileName);
            }
            if (!file_exists($fileName)) {
                echo json_encode([
                    'code' => 0, 'msg' => '文件合并失败', 'filePath' => $fileName,
                ]);exit;
            }
            exec("cp $fileName $finalFileName");
            unlink($fileName);
            echo json_encode([
                'code' => 1, 'msg' => 'success', 'filePath' => $finalFileName,
            ]);exit;
        } else {
            echo json_encode([
                'code' => 1, 'msg' => 'continue', 'detail' => $chunkIndex.'|'.$totalChunks,
            ]);exit;
        }
    } else {
        echo json_encode([
            'code' => 0, 'msg' => 'fail', 'detail' => 'fail',
        ]);exit;
    }
} catch (\Throwable $th) {
    echo $th->getMessage();
    var_dump($th->getTraceAsString());
}
exit;    
?>
